simulation.ts ➔ dragged   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 4
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
1
import { DependencyLink, DependencyNode } from '../../components/types';
2
import { forceCenter, forceCollide, forceLink, forceSimulation, forceY, Simulation } from 'd3-force';
3
import { drag } from 'd3-drag';
4
import { selectHighLightedNodes } from '../../utils/helpers/Selectors';
5
import { event } from 'd3-selection';
6
import { hideTooltip, showTooltip } from '../tooltip/tooltip';
7
8
export function createSimulation(nodes: DependencyNode[], links: DependencyLink[], width: number, height: number) {
9
    return forceSimulation(nodes)
10
        .force(
11
            'dependency',
12
            forceLink<DependencyNode, DependencyLink>(links)
13
                .distance(180)
14
                .id((node: DependencyNode) => node.name)
15
        )
16
        .alphaDecay(0.1)
17
        .force('center', forceCenter(width / 2, height / 2))
18
        .force('y', forceY(0.5))
19
        .force('collide', forceCollide(140))
20
        .force('nodeCollide', forceCollide(140));
21
}
22
23
export function addNodesDrag(simulation: Simulation<DependencyNode, DependencyLink>) {
24
    let isDragStarted = false;
25
    return drag<SVGGElement, DependencyNode>()
26
        .on('start', (node: DependencyNode) => {
27
            if (!selectHighLightedNodes().data().length) {
28
                dragStarted(node, simulation);
29
                isDragStarted = true;
30
                hideTooltip();
31
            }
32
        })
33
        .on('drag', (node: DependencyNode) => {
34
            if (isDragStarted) {
35
                dragged(node);
36
            }
37
        })
38
        .on('end', (node: DependencyNode) => {
39
            dragEnded(node, simulation);
40
            isDragStarted = false;
41
            showTooltip();
42
        });
43
}
44
45
function dragStarted(node: DependencyNode, simulation: Simulation<DependencyNode, DependencyLink>) {
46
    if (!event.active) {
47
        simulation.alphaTarget(0.3).restart();
48
    }
49
    node.fx = node.x;
50
    node.fy = node.y;
51
}
52
53
function dragged(node: DependencyNode) {
54
    node.fx = event.x;
55
    node.fy = event.y;
56
}
57
58
function dragEnded(node: DependencyNode, simulation: Simulation<DependencyNode, DependencyLink>) {
59
    if (!event.active) {
60
        simulation.alphaTarget(0);
61
    }
62
    node.fx = null;
63
    node.fy = null;
64
}
65